package com.jerry.boot.admin.api.shiro;

import com.jerry.db.domain.BootUserInfo;
import com.jerry.db.service.BootPermissionInfoService;
import com.jerry.db.service.BootRoleInfoService;
import com.jerry.db.service.BootUserInfoService;
import com.jerry.frame.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

//可以参照JDBCRealm来实现校验过程
public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Resource
    private BootRoleInfoService bootRoleInfoService;
    @Resource
    private BootPermissionInfoService bootPermissionInfoService;
    @Resource
    private BootUserInfoService bootUserInfoService;
    @Override
    //权限验证
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        BootUserInfo admin = (BootUserInfo) getAvailablePrincipal(principals);
        String[] roleIds = admin.getRoleIds();
        Set<String> roles = bootRoleInfoService.queryByIds(roleIds);
        Set<String> permissions = bootPermissionInfoService.queryByRoleIds(roleIds);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    //身份验证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        String password=new String(upToken.getPassword());

        if (StringUtils.isEmpty(username)) {
            throw new AccountException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new AccountException("密码不能为空");
        }

        List<BootUserInfo> adminList = bootUserInfoService.findByAccount(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.size() == 0) {
            throw new UnknownAccountException("找不到用户（"+username+"）的帐号信息");
        }
        BootUserInfo admin = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, admin.getPassword())) {
            throw new UnknownAccountException("找不到用户（"+username+"）的帐号信息");
        }

        return new SimpleAuthenticationInfo(admin,password,getName());
    }
}
